#include "FKObjectsData.h"

#include "FKObject.h"

#include <QDataStream>

#include "FKLogger.h"

int FKObjectsData::sInit=FKObjectsData::declareFKMetaType();

int FKObjectsData::declareFKMetaType(){
    qRegisterMetaTypeStreamOperators<FKObjectsData>("FKObjectsData");
    qRegisterMetaTypeStreamOperators<QList<qint32> >("QList<qint32>");
    qRegisterMetaType<QList<qint32> >("QList<qint32>");
    return qRegisterMetaType<FKObjectsData>();
}

FKObjectsData::FKObjectsData():
        _indexIterator(_indexes),_objectsIterator(_objects),_classnameIterator(_classNames){

}

FKObjectsData::FKObjectsData(const FKObjectsData &other):
        _roomList(other._roomList),_indexes(other._indexes),
        _objects(other._objects),_classNames(other._classNames),
        _indexIterator(_indexes),_objectsIterator(_objects),_classnameIterator(_classNames){
//    resetIterators();
}

FKObjectsData::FKObjectsData(QSet<FKObject*> objects):
        _indexIterator(_indexes),_objectsIterator(_objects),_classnameIterator(_classNames){
//    int size=objects.size();
//    _indexes.resize(size);
//    _objects.resize(size);
//    _classNames.resize(size);
    qint32 i(0), cur(0);
    foreach(FKObject* obj, objects){
        cur=_roomList.indexOf(obj->getRoomID());
        if(cur==-1){
            _roomList.append(obj->getRoomID());
            cur=i++;
        }
        _indexes.append(cur);
        _objects.append(obj->getID());
        _classNames.append(obj->getClassName());
    }
    resetIterators();
}

void FKObjectsData::resetIterators(){
    _indexIterator.toFront();
    _objectsIterator.toFront();
    _classnameIterator.toFront();
}

bool FKObjectsData::getNext(QString &className, qint32 &roomIndex, qint32 &id){
    if(_indexIterator.hasNext()){
        roomIndex=_indexIterator.next();
        id=_objectsIterator.next();
        className=_classnameIterator.next();
        FK_MLOGV("object parsed for creation",className+QString::number(id))
        return true;
    }else{
        FK_MLOG("end data object")
        resetIterators();
        return false;
    }
}

QList<qint32> FKObjectsData::roomList(){
    return _roomList;
}

QDataStream& operator<<(QDataStream &stream,const FKObjectsData &data){
    stream<<data._roomList;
    stream<<data._indexes;
    stream<<data._objects;
    stream<<data._classNames;
    return stream;
}

QDataStream& operator>>(QDataStream &stream, FKObjectsData &data){
    stream>>data._roomList;
    stream>>data._indexes;
    stream>>data._objects;
    stream>>data._classNames;
    data.resetIterators();
    return stream;
}

QDataStream& operator<<(QDataStream &stream,const QList<qint32> &data){
    stream<<data.size();
    foreach(qint32 i,data)stream<<i;
    return stream;
}

QDataStream& operator>>(QDataStream &stream, QList<qint32> &data){
    qint32 size, v;
    stream>>size;
    for(int i=0;i<size;++i){
        stream>>v;
        data.append(v);
    }
    return stream;
}
